#include<iostream>
#include<pthread.h>
#include<vector>
#include<unistd.h>
#include<cstdio>
#include<string.h>
using namespace std;

int tickets = 1000;//多线程模拟抢票

#define NUM 4

class ThreadData
{
public:
    ThreadData(int number,  pthread_mutex_t *mutex)
    {
        _threadname = "thread-"+ to_string(number);
        _lock = mutex;
    }

public:
    string _threadname;
    pthread_mutex_t *_lock;
};


void* GetTicket(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    const char *name = td->_threadname.c_str();
    int cnt = 5;
    while(true)
    {
        pthread_mutex_lock(td->_lock);
        if(tickets > 0)
        {
            usleep(1000);
            printf("who = %s, get a ticket : %d\n", name, tickets);
            tickets--;
            pthread_mutex_unlock(td->_lock);
        }
        else
        {
            pthread_mutex_unlock(td->_lock);
            break;
        }
        usleep(13);

    }
    return nullptr;
}

int main()
{
    pthread_mutex_t lock;
    pthread_mutex_init(&lock, nullptr);

    vector<pthread_t> tids;
    vector<ThreadData*>thread_datas;
    for(int i = 1; i <= NUM; i++)
    {
        pthread_t tid;
        ThreadData *td = new ThreadData(i, &lock);
        thread_datas.push_back(td);
        pthread_create(&tid, nullptr, GetTicket, td);
        tids.push_back(tid);
    }

    for(auto thread: tids)
    {
        pthread_join(thread, nullptr);
    }
    for(auto td: thread_datas)
    {
        delete td;
    }
    //关锁
    pthread_mutex_destroy(&lock);
    return 0;
}















// #define NUM 10

// struct ThreadData
// {
//     string _tid;
//     string _threadname;
// };


// void *ThreadRoutine(void *args)
// {
//     ThreadData *td = static_cast<ThreadData *>(args);
//     int i = 0;
//     while(i < 10)
//     {
//         cout<<"pid: "<<getpid()<<", "<<td->_threadname<<endl;
//         sleep(1);
//         i++;
//     }
//     return nullptr;
// }

// void InitThreadData(ThreadData *td, int i, pthread_t tid)
// {
//     td->_threadname = "thread-"+to_string(i);

//     char buffer[128];
//     snprintf(buffer, sizeof(buffer),"0x%x",tid);
// }

// int main()
// {
//     vector<pthread_t> tids;
//     for(int i = 0; i < NUM; i++)
//     {
//         pthread_t tid;
//         ThreadData *td = new ThreadData;
//         InitThreadData(td, i, tid);
//         pthread_create(&tid, nullptr, ThreadRoutine, td);
//         tids.push_back(tid);
//     }

//     for(auto e: tids)
//     {
//         pthread_detach(e);
//     }

//     for(int i = 0; i < tids.size(); i++)
//     {
//         int n = pthread_join(tids[i], nullptr);
//         printf("n = %d, who = %x\n, why: ", n, tids[i], strerror(n));
//     }
//     return 0;
// }